//
//  ViewController.swift
//  微博表情键盘
//
//  Created by Summer on 2017/12/22.
//  Copyright © 2017年 Summer. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    // self 引用 emoticonInputView，emoticonInputView 引用闭包，闭包引用 self，循环引用
    lazy var emoticonInputView = CZEmoticonInputView.emoticonInputView {[weak self] (em) in
        self?.insertEmoticon(em: em)
    }
    
    /// 向文本视图插入表情符号
    ///
    /// - Parameter em: CZEmoticon
    func insertEmoticon(em: CZEmoticon?) {
        
        // 1.删除按钮
        guard let em = em else {
            
            textView.deleteBackward()
            return
        }
        
        // 2.emoji 字符串
        if let emoji = em.emoji, let textRange = textView.selectedTextRange {
            textView.replace(textRange, withText: emoji)
            return
        }
        
        // 3.图片表情
        let imageText = em.imageText(font: textView.font!)
        let attrStrM = NSMutableAttributedString(attributedString: textView.attributedText)
        attrStrM.replaceCharacters(in: textView.selectedRange, with: imageText)
        // 记录光标位置
        let selectedRange = textView.selectedRange
        
        textView.attributedText = attrStrM
        
        // 恢复光标位置，length是选中字符的长度，插入文本之后应该为0
        textView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        textView.inputView = emoticonInputView
        
    }

    // MARK: 转换字符串
    @IBAction func show(_ sender: Any) {
        print(emoticonText)
    }
    
    /// 属性字符串--计算型属性
    //  比如："123[爱你]321"
    var emoticonText: String {
        
        guard let attrStr = textView.attributedText else {
            return ""
        }
        
        // 遍历enumerate
        var result = String()
        attrStr.enumerateAttributes(in: NSRange(location: 0, length: attrStr.length), options: []) { (dict, range, _) in
            
            // 图片表情
            if let attachment = dict[NSAttributedStringKey.attachment] as? CZTextAttachment {
                // 从 attachment 获取 chs
                result += attachment.chs ?? ""
            } else {
                let subStr = (attrStr.string as NSString).substring(with: range)
                result += subStr
            }
        }
        
        return result
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }


}

